/*
 * @Author: zhangrui BruceZhang@huayun.com
 * @Date: 2023-07-18 13:12:54
 * @LastEditors: zhangrui BruceZhang@huayun.com
 * @LastEditTime: 2023-07-18 19:53:08
 * @FilePath: \alkaid-rgy\launch\launch.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package launch

import (
	"fmt"
	"os"

	"golang.org/x/sys/windows/registry"
)

// 注册表项路径
var keyPath = `SOFTWARE\Microsoft\Windows\CurrentVersion\Run`
var exeName = "alkaid_rgy"

func OpenLaunch() {

	// 可执行文件路径
	executablePath, _ := os.Executable()

	// 创建注册表项并设置可执行文件路径
	k, err := registry.OpenKey(registry.CURRENT_USER, keyPath, registry.ALL_ACCESS)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer k.Close()

	// 设置注册表项的值
	path := fmt.Sprintf("\"%s\" %s", executablePath, " -autorun")
	err = k.SetStringValue(exeName, path)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("自启动已配置")
}

func CloseLaunch() {

	// 打开注册表项
	k, err := registry.OpenKey(registry.CURRENT_USER, keyPath, registry.ALL_ACCESS)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer k.Close()

	// 删除注册表项
	err = k.DeleteValue(exeName)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("自启动已取消")
}

func CheckLaunch() bool {

	// 打开注册表项
	k, err := registry.OpenKey(registry.CURRENT_USER, keyPath, registry.READ)
	if err != nil {
		fmt.Println(err)
		return false
	}
	defer k.Close()

	// 检查注册表项是否存在
	_, _, err = k.GetStringValue(exeName)
	if err == nil {
		fmt.Println("已设置开机自启动")
		return true
	} else if err == registry.ErrNotExist {
		fmt.Println("未设置开机自启动")
		return false
	} else {
		fmt.Println("检查开机自启动状态失败:", err)
		return false
	}
}
